from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.db.models import User, Resume, JobDescription
from app.schemas import (
    AIOptimizationRequest,
    JobDescription as JobDescriptionSchema,
    JobDescriptionCreate
)
from app.crud import (
    get_resume,
    get_job_description,
    create_job_description,
    update_job_description
)
from app.core.security import get_current_active_user
from app.services.ai_service import ai_client

# 创建AI服务路由器
router = APIRouter()

# 分析职位描述
@router.post("/analyze-job-description", response_model=dict)
def analyze_job_description(
    job_description_id: Optional[int] = None,
    job_description_text: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    分析职位描述，提取关键信息
    可以通过职位描述ID或直接提供职位描述文本进行分析
    """
    if not job_description_id and not job_description_text:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Either job_description_id or job_description_text must be provided"
        )
    
    # 获取职位描述内容
    if job_description_id:
        db_job_description = get_job_description(db, job_description_id=job_description_id)
        if db_job_description is None:
            raise HTTPException(status_code=404, detail="Job description not found")
        jd_content = db_job_description.content
    else:
        jd_content = job_description_text
    
    # 调用AI分析服务
    analysis_result = ai_client.analyze_job_description(jd_content)
    
    if not analysis_result:
        raise HTTPException(status_code=500, detail="AI analysis failed")
    
    # 如果是通过ID分析，保存分析结果
    if job_description_id:
        # 提取关键技能（如果有）
        key_skills = None
        if isinstance(analysis_result, dict) and 'key_skills' in analysis_result:
            import json
            key_skills = json.dumps(analysis_result['key_skills'])
        elif isinstance(analysis_result, dict) and 'analysis_text' in analysis_result:
            key_skills = analysis_result['analysis_text']
        
        if key_skills:
            update_job_description(db=db, db_job_description=db_job_description, key_skills=key_skills)
    
    return {
        "success": True,
        "analysis_result": analysis_result
    }

# 优化简历内容
@router.post("/optimize-resume", response_model=dict)
def optimize_resume_content(
    request: AIOptimizationRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    根据职位描述优化简历内容
    支持整体优化、经验优化、技能优化和总结优化
    """
    # 获取简历
    db_resume = get_resume(db, resume_id=request.resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    
    # 获取职位描述内容
    jd_content = None
    if request.job_description_id:
        db_job_description = get_job_description(db, job_description_id=request.job_description_id)
        if db_job_description is None:
            raise HTTPException(status_code=404, detail="Job description not found")
        jd_content = db_job_description.content
    elif request.job_description_text:
        jd_content = request.job_description_text
    
    if not jd_content:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Either job_description_id or job_description_text must be provided"
        )
    
    # 构建简历内容字符串
    resume_content = build_resume_content_for_optimization(db_resume, db)
    
    # 调用AI优化服务
    optimized_content = ai_client.optimize_resume_content(
        resume_content=resume_content,
        jd_content=jd_content,
        optimization_type=request.optimization_type
    )
    
    if not optimized_content:
        raise HTTPException(status_code=500, detail="AI optimization failed")
    
    # 根据优化类型，解析并更新简历信息
    # 注：这里简化了实现，实际应用中需要根据优化结果的格式进行解析和更新
    update_result = update_resume_with_optimized_content(
        db_resume=db_resume,
        optimized_content=optimized_content,
        optimization_type=request.optimization_type,
        db=db
    )
    
    return {
        "success": True,
        "optimized_content": optimized_content,
        "update_result": update_result
    }

# 生成简历总结
@router.post("/generate-summary", response_model=dict)
def generate_resume_summary(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    根据简历内容生成专业的个人总结
    """
    # 获取简历
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    
    # 构建简历内容字符串
    resume_content = build_resume_content_for_optimization(db_resume, db)
    
    # 调用AI生成服务
    generated_summary = ai_client.generate_resume_summary(resume_content)
    
    if not generated_summary:
        raise HTTPException(status_code=500, detail="AI summary generation failed")
    
    return {
        "success": True,
        "summary": generated_summary
    }

# 获取关键词建议
@router.post("/suggest-keywords", response_model=dict)
def suggest_keywords(
    resume_id: int,
    job_description_id: Optional[int] = None,
    job_description_text: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    根据简历和职位描述，推荐应该包含的关键词
    """
    # 获取简历
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    
    # 获取职位描述内容
    jd_content = None
    if job_description_id:
        db_job_description = get_job_description(db, job_description_id=job_description_id)
        if db_job_description is None:
            raise HTTPException(status_code=404, detail="Job description not found")
        jd_content = db_job_description.content
    elif job_description_text:
        jd_content = job_description_text
    
    if not jd_content:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Either job_description_id or job_description_text must be provided"
        )
    
    # 构建简历内容字符串
    resume_content = build_resume_content_for_optimization(db_resume, db)
    
    # 调用AI关键词建议服务
    suggested_keywords = ai_client.suggest_keywords(
        resume_content=resume_content,
        jd_content=jd_content
    )
    
    if suggested_keywords is None:
        raise HTTPException(status_code=500, detail="AI keyword suggestion failed")
    
    return {
        "success": True,
        "keywords": suggested_keywords
    }

# 辅助函数：构建简历内容字符串用于AI处理
def build_resume_content_for_optimization(db_resume: Resume, db: Session) -> str:
    """\构建简历内容字符串用于AI处理"""
    content_parts = []
    
    # 添加个人信息
    if db_resume.personal_info:
        pi = db_resume.personal_info
        content_parts.append(f"个人信息：\n姓名：{pi.full_name}\n邮箱：{pi.email}\n电话：{pi.phone}\n地址：{pi.address}\n")
        if pi.summary:
            content_parts.append(f"个人总结：{pi.summary}\n")
    
    # 添加教育经历
    if db_resume.education:
        content_parts.append("教育经历：\n")
        for edu in db_resume.education:
            content_parts.append(f"- {edu.degree}，{edu.major}，{edu.institution}，{edu.start_date} - {edu.end_date}\n")
            if edu.description:
                content_parts.append(f"  描述：{edu.description}\n")
    
    # 添加工作经历
    if db_resume.work_experience:
        content_parts.append("工作经历：\n")
        for exp in db_resume.work_experience:
            content_parts.append(f"- {exp.position}，{exp.company}，{exp.start_date} - {exp.end_date}\n")
            if exp.description:
                content_parts.append(f"  描述：{exp.description}\n")
            if exp.achievements:
                content_parts.append(f"  成就：{exp.achievements}\n")
    
    # 添加技能
    if db_resume.skills:
        content_parts.append("技能：\n")
        skills_text = ", ".join([f"{skill.name}（熟练程度：{skill.level}/5）" for skill in db_resume.skills])
        content_parts.append(f"{skills_text}\n")
    
    # 添加证书
    if db_resume.certificates:
        content_parts.append("证书：\n")
        for cert in db_resume.certificates:
            content_parts.append(f"- {cert.name}，{cert.issuing_authority}，{cert.issue_date}\n")
    
    return "\n".join(content_parts)

# 辅助函数：更新简历信息

def update_resume_with_optimized_content(
    db_resume: Resume,
    optimized_content: str,
    optimization_type: str,
    db: Session
) -> dict:
    """\更新简历信息"""
    # 这里简化了实现，实际应用中需要根据优化结果的格式进行解析和更新
    # 例如，可以解析JSON格式的优化结果，然后更新对应的数据库字段
    
    # 对于文本格式的优化结果，可以根据优化类型进行不同的处理
    if optimization_type == "summary" and db_resume.personal_info:
        # 提取总结部分并更新
        # 这里需要根据实际的返回格式进行解析
        db_resume.personal_info.summary = optimized_content
        db.commit()
        db.refresh(db_resume.personal_info)
        return {"updated_field": "personal_info.summary"}
    
    # 对于其他类型的优化，可能需要更复杂的解析逻辑
    # 这里返回一个简化的结果
    return {"message": f"Resume optimized for {optimization_type}"}